package com.lalilu.lmedia.repository

import com.lalilu.lmedia.entity.LSong
import com.lalilu.lmedia.wrapper.Taglib
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

interface LyricSource {
    suspend fun loadLyric(song: LSong): Pair<String, String?>?
}


class LyricSourceFactory(
    private vararg val sources: LyricSource
) : LyricSource {
    override suspend fun loadLyric(song: LSong): Pair<String, String?>? =
        withContext(Dispatchers.IO) { sources.firstNotNullOfOrNull { it.loadLyric(song) } }
}

class LyricSourceEmbedded : LyricSource {
    override suspend fun loadLyric(song: LSong): Pair<String, String?>? =
        withContext(Dispatchers.IO) {
            val songData = song.pathStr ?: return@withContext null
            val lyric = Taglib.getLyric(songData)

            if (lyric.isNullOrBlank()) return@withContext null
            lyric to null
        }
}

class LyricSourceLocal : LyricSource {
    override suspend fun loadLyric(song: LSong): Pair<String, String?>? =
        withContext(Dispatchers.IO) {
            val songData = song.pathStr ?: return@withContext null
            val path = songData.substring(0, songData.lastIndexOf('.')) + ".lrc"
            val lrcFile = File(path)

            if (!lrcFile.exists()) return@withContext null

            val lyric = lrcFile.readText()
            if (lyric.isBlank()) return@withContext null
            lyric to null
        }
}


